package com.apps.ftapp.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.Singleton;
import com.apps.ftapp.adapter.SubjectResultAdapter;
import com.apps.ftapp.adapter.SucModelAdapter;
import com.apps.ftapp.model.LianXiTiModel;
import com.apps.ftapp.model.LianXiTiModel1;
import com.apps.ftapp.model.SubjectResultModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

/**
 * 练习报告
 */
public class SubjectResultActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.score)
    TextView score;
    @BindView(R.id.max_score)
    TextView maxScore;
    @BindView(R.id.max_score_num)
    TextView maxScoreNum;
    @BindView(R.id.avg_score)
    TextView avgScore;
    @BindView(R.id.avg_score_num)
    TextView avgScoreNum;
    @BindView(R.id.gridView)
    GridView gridView;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.cuotijiexi)
    TextView cuotijiexi;
    @BindView(R.id.quanbujiexi)
    TextView quanbujiexi;
    @BindView(R.id.jixudati)
    TextView jixudati;
    private Gson gson = new Gson();

    private String paperResultId;
    private String categoryId;

    private SubjectResultAdapter subjectResultAdapter;

    private List<LianXiTiModel.TestResultsBean> dataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subject_result);
        ButterKnife.bind(this);
        setTitle("练习报告");


        initView();
        loadData();


    }

    private void initView() {
        subjectResultAdapter = new SubjectResultAdapter(getApplicationContext(), dataList);
        gridView.setAdapter(subjectResultAdapter);

        cuotijiexi.setOnClickListener(this);
        quanbujiexi.setOnClickListener(this);
        jixudati.setOnClickListener(this);
    }

    /**
     * 提交
     */
    public void loadData() {
        Singleton s = Singleton.getInstance();
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("id", s.getId());
        params.put("beginTime", s.getStartTime());
        params.put("endTime", s.getEndTime());

        L.i("main", s.getStartTime());
        L.i("main", Tools.getTime());
        L.i("main", s.getId());
        String cha = Tools.getcha(s.getStartTime(), s.getEndTime());
        avgScoreNum.setText(cha);
        //json格式， （答案A值为0，B值为1，C值为2，D值为3；例如：id 为试题id；ans 为答案
        // json格式案例：[ { "id" : "538", "ans" : "0" }, { "id" : "539", "ans" : "0,1,2" }.....],

        L.i("main", ",,,," + gson.toJson(s.getDatas()));
        params.put("Answers", gson.toJson(s.getDatas()));
        params.put("usedTime", 10);
        Async.post("tiku/finish", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", "结果：" + new String(responseBody));
                    // ActivitySkipUtil.skipAnotherActivity(GestureFilpActivity.this,SubjectResultActivity.class,true);

                    LianXiTiModel result = new LianXiTiModel();
                    try {
                        result = gson.fromJson(new String(responseBody), LianXiTiModel.class);
                    } catch (Exception e) {
                        LianXiTiModel1 result1 = gson.fromJson(new String(responseBody), LianXiTiModel1.class);
                        //
                        result.setSuccess(result1.getSuccess());
                        result.setUsedtime(result1.getUsedtime());
                        result.setZhengquelv(result1.getZhengqueshu());
                        result.setZongshu(result1.getZongshu());
                        result.setZhengqueshu(result1.getZhengqueshu());
                        LianXiTiModel1.ResultsBean resultsBean1 = result1.getResults();
                        LianXiTiModel.ResultsBean resultsBean = new LianXiTiModel.ResultsBean();
                        if (null != result1.getResults()) {
                            resultsBean.setActive(resultsBean1.getActive());
                            resultsBean.setBeginTime(resultsBean1.getBeginTime());
                            resultsBean.setCategoryId(resultsBean1.getCategoryId());
                            resultsBean.setCheckedTime(resultsBean1.getCheckedTime());
                            resultsBean.setCheckTeacherId(resultsBean1.getCheckTeacherId());
                            resultsBean.setId(resultsBean1.getId());
                            resultsBean.setLimitedTime(resultsBean1.getLimitedTime());
                            resultsBean.setObjectiveScore(resultsBean1.getObjectiveScore());
                            resultsBean.setUserId(resultsBean1.getUserId());
                            resultsBean.setTestId(resultsBean1.getTestId());
                            resultsBean.setStatus(resultsBean1.getStatus());
                            resultsBean.setTarget(resultsBean1.getTarget());
                            resultsBean.setScore(resultsBean1.getScore());
                            resultsBean.setUpdateTime(resultsBean1.getUpdateTime());
                        }
                        result.setResults(resultsBean);
                        //
                        List<LianXiTiModel.TestResultsBean> beans = new ArrayList<LianXiTiModel.TestResultsBean>();
                        if (null != result1.getTestResults() && result1.getTestResults().size() > 0) {
                            for (LianXiTiModel1.TestResultsBean bean1 : result1.getTestResults()) {
                                LianXiTiModel.TestResultsBean bean = new LianXiTiModel.TestResultsBean();
                                bean.setScore(bean1.getScore());
                                bean.setStatus(bean1.getStatus());
                                bean.setAnswer(new ArrayList<>());
                                bean.setId(bean1.getId());
                                bean.setItemId(bean1.getItemId());
                                bean.setPId(bean1.getPId());
                                bean.setQuestion_category(bean1.getQuestion_category());
                                bean.setRightan(bean1.getRightan());
                                bean.setUserId(bean1.getUserId());
                                bean.setTestId(bean1.getTestId());
                                bean.setQuestionId(bean1.getQuestionId());
                                bean.setTeacherSay(bean1.getTeacherSay());
                                beans.add(bean);
                            }
                        }
                        result.setTestResults(beans);


                    }

                    if (1 == Tools.isIntNull(result.getSuccess())) {


                        paperResultId = result.getResults().getId();
                        score.setText(result.getZhengquelv() + "");
                        maxScoreNum.setText(result.getZhengqueshu() + "/" + result.getZongshu() + "题 ");
//                        avgScoreNum.setText(result.getUsedtime());


                        categoryId = result.getResults().getCategoryId();

                        subjectResultAdapter.addRes(result.getTestResults());
                    } else {

//                        Toasty.normal(getApplicationContext(), result.getError()).show();
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cuotijiexi:
                HashMap map1 = new HashMap();
                map1.put("id", paperResultId);
//                ActivitySkipUtil.skipAnotherActivity(SubjectResultActivity.this,CuotiJieXiActivity.class,map1);
                ActivitySkipUtil.skipAnotherActivity(SubjectResultActivity.this, StErrorJxActivity.class, map1);

                break;

            case R.id.quanbujiexi:
                //全部错题
                HashMap map = new HashMap();
                map.put("id", paperResultId);
//                ActivitySkipUtil.skipAnotherActivity(SubjectResultActivity.this,CuotiAllActivity.class,map);
                ActivitySkipUtil.skipAnotherActivity(SubjectResultActivity.this, CuotiAllJxActivity.class, map);

                break;

            case R.id.jixudati:

                HashMap<String, Object> data = new HashMap<String, Object>();
                data.put("id", categoryId);

                Singleton singleton = Singleton.getInstance();
                data.put("keys", singleton.getKeys());
                data.put("lmname", singleton.getLmname());

                L.i("main", singleton.getKeys() + "==============" + singleton.getKeys());

                if ("1".equals(Tools.isNull(Singleton.getType()))) {
                    ActivitySkipUtil.skipAnotherActivity(SubjectResultActivity.this, SubjectZdTkuActivity.class, data);
                } else {
                    ActivitySkipUtil.skipAnotherActivity(SubjectResultActivity.this, SubjectZdActivity.class, data);
                }
//                data.put("keys",keys);


                break;
        }
    }
}
